import { ref } from "vue";
import { useRouter } from "vue-router";
import { loginAPI, registerAPI, getOneAPI } from "@/apis/user.js";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user.js";
import { debounce } from "@/utils/shakeAndThrottle.js";

export function userLogin() {
  const userStore = useUserStore();

  //准备表单对象
  const loginForm = ref({
    phone: "18171964981",
    password: "123456",
  });
  const registerForm = ref({
    name: "",
    phone: "17740616201",
    sex: "男",
    password: "123456",
    confirmPassword: "123456",
    file: "",
  });

  //准备规则对象
  const loginRules = {
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      {
        required: true,
        pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
        message: "手机号格式不正确",
        trigger: "blur",
      },
    ],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      { min: 6, max: 14, message: "密码长度为6-14个字符", trigger: "blur" },
    ],
  };
  const registerRules = {
    name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      {
        required: true,
        pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
        message: "手机号格式不正确",
        trigger: "blur",
      },
    ],
    sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      { min: 6, max: 14, message: "密码长度为6-14个字符", trigger: "blur" },
    ],
    confirmPassword: [
      { required: true, message: "密码不能为空", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          //自定义校验逻辑
          //校验两次密码
          if (value === registerForm.value.password) {
            callback();
          } else {
            callback(new Error("两次密码不同"));
          }
        },
      },
    ],
  };

  //获取form实例做统一校验
  const loginFormRef = ref(null);
  const registerFormRef = ref(null);

  const router = useRouter();

  //是否弹窗
  const dialogFormVisible = ref(false);
  //弹窗表格对象
  const tableForm = ref({
    phone: "18888888888",
    password: "123456",
  });

  //保存图片
  const uploadImg = (file) => {
    registerForm.value.file = file.file;
  };

  // 用户信息
  const user = ref({
    id: "",
    name: "",
    sex: "",
    phone: "",
    site: "",
    portrait: "",
  });

  // 登录 | 注册
  const doLogin = debounce((value) => {
    if (value === "login") {
      // 登录
      const { phone, password } = loginForm.value;
      loginFormRef.value.validate(async (valid) => {
        //valid: 所有表单都通过检验才为true
        //通过校验
        if (valid) {
          //登录
          RLogin(phone, password);
        }
      });
    } else {
      // 注册
      registerFormRef.value.validate(async (valid) => {
        //valid: 所有表单都通过检验才为true
        //通过校验
        if (valid) {
          // 注册
          const result = await registerAPI(registerForm.value);

          if (result) {
            //提示用户
            ElMessage({ type: "success", message: "注册成功" });

            RLogin(registerForm.value.phone, registerForm.value.password);
          }
        }
      });
    }
  });

  // 登录逻辑
  const RLogin = async (phone, password) => {
    //登录
    const result = await loginAPI({ phone, password });

    if (result) {
      // 解析token
      let token = result.data;

      let strings = token.split(".");
      let userinfo = JSON.parse(
        decodeURIComponent(
          escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))
        )
      );
      let userId = userinfo.sub;

      userStore.setUserToken(token);

      const resp = await getOneAPI(userId);
      user.value = resp.data;

      userStore.setUserInfo(user.value);

      ElMessage({ type: "success", message: "登录成功" });
      //跳转
      router.replace({ path: "/" });
    }
  };

  return {
    loginForm,
    registerForm,
    loginRules,
    registerRules,
    loginFormRef,
    registerFormRef,
    dialogFormVisible,
    tableForm,
    doLogin,
    uploadImg,
  };
}
